package com.qiyun.framework.helper;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.util.DisplayMetrics;
import android.widget.ImageView;


import com.qiyun.framework.R;
import com.qiyun.framework.utils.CameraUtils;

import org.xutils.ImageManager;
import org.xutils.image.ImageOptions;
import org.xutils.x;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import static android.provider.MediaStore.Files.FileColumns.MEDIA_TYPE_IMAGE;

/**
 * Bitmap通用功能管理类
 * Created by Tiger on 2015/12/15.
 */
public class BitmapHelper {
    private static ImageManager bitmapUtils;
    private static ImageOptions imageOptions;
    /**
     * 初始化bitmapUtils
     * @param context
     * @return
     */
    public static void init(Context context){
        if(bitmapUtils==null) {
            bitmapUtils = x.image();
        }
    }

    /**
     * 获取
     * @return
     */
    public static ImageManager getBitmapUtils(){
        return bitmapUtils;
    }



    /**
     * 获取显示配置
     * @param context
     * @return
     */
    public static ImageOptions getCommonImageOptions(Context context){
        if(imageOptions!=null) return imageOptions;
        return imageOptions = new ImageOptions.Builder()
                // 如果ImageView的大小不是定义为wrap_content, 不要crop.
                //.setCrop(true) // 很多时候设置了合适的scaleType也不需要它.
                // 加载中或错误图片的ScaleType
                //.setPlaceholderScaleType(ImageView.ScaleType.MATRIX)
                .setImageScaleType(ImageView.ScaleType.CENTER)
                .setLoadingDrawableId(R.mipmap.ic_launcher)
                .setFailureDrawableId(R.mipmap.ic_launcher)
                .build();
    }




    /**
     * 根据分辨率剪裁
     */
    public static Bitmap imageCrop(Activity context, Bitmap bitmap) {
        int w = bitmap.getWidth(); // 得到图片的宽，高
        int h = bitmap.getHeight();
        float wh = (float) getWidth(context) / (float) getHeight(context); // 屏幕的宽高比
        int w2 = (int) (wh * h); // 分比率比例换算后的宽的差值
        int retX = 0;
        if (w2 > w) { // 宽度不够剪裁，原始大小
            return bitmap;
        }
        retX = (w - w2) / 2;// 基于原图，取左上角x坐标
        // 下面这句是关键
        return Bitmap.createBitmap(bitmap, retX, 0, w2, h, null, false);
    }
    /**
     * 获取屏幕宽度
     */
    public static int getWidth(Activity context) {
        DisplayMetrics dm = new DisplayMetrics();
        context.getWindowManager().getDefaultDisplay().getMetrics(dm);
        return dm.widthPixels;
    }

    /**
     * 获取屏幕高度
     */
    public static int getHeight(Activity context) {
        DisplayMetrics dm = new DisplayMetrics();
        context.getWindowManager().getDefaultDisplay().getMetrics(dm);
        return dm.heightPixels;
    }


    /**
     * 以最省内存的方式读取本地资源的图片
     *
     * @param context
     * @param resId
     * @return
     */
    public static Bitmap readBitMap(Context context, int resId) {
        BitmapFactory.Options opt = new BitmapFactory.Options();
        opt.inPreferredConfig = Bitmap.Config.RGB_565;
        int height = getHeight((Activity) context);
        if (height < 1920) {
            opt.inSampleSize = (1920 + height - 1) / height;
        }
        opt.inPurgeable = true;
        opt.inInputShareable = true;
        // 获取资源图片
        InputStream is = null;
        Bitmap bitmap = null;
        try {
            is = context.getResources().openRawResource(resId);
            bitmap = imageCrop((Activity) context, BitmapFactory.decodeStream(is, null, opt));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return bitmap;
    }


    /** 保存方法 */
    public static void saveBitmap(Context context, Bitmap bitmap, String picName) {
        File f = new File(StorageHelper.getExternalImageCacheDir(context), picName);
        if (!f.exists()) {
            return;
        }
        try {
            FileOutputStream out = new FileOutputStream(f);
            bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
            out.flush();
            out.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    //获取bitmap
    public static Bitmap getBitmap(String imgPath) {
        // Get bitmap through image path
        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        newOpts.inJustDecodeBounds = false;
        newOpts.inPurgeable = true;
        newOpts.inInputShareable = true;
        // Do not compress
        newOpts.inSampleSize = 1;
        newOpts.inPreferredConfig = Bitmap.Config.RGB_565;
        return BitmapFactory.decodeFile(imgPath, newOpts);
    }

    /**
     * 压缩图片
     * @param picPath
     */
    public static Uri compressPicture(String picPath){
        File f = new File(picPath);
        if (!f.exists()) {
            return null;
        }
        try {
            Bitmap bitmap=getBitmap(picPath);
            Uri newFileUri= CameraUtils.getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
            File file=new File(newFileUri.getPath());
            //创建文件压缩图片
            if(file.createNewFile()){
                FileOutputStream out = new FileOutputStream(file);
                bitmap.compress(Bitmap.CompressFormat.JPEG, 40, out);
                out.flush();
                out.close();
                //删除原文件
                f.delete();
                return newFileUri;
            }else{
                return null;
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
